using System;
using System.Data;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;

/// <summary>
/// Summary description for CheckBoxListEx
/// </summary>
public class CheckBoxListEx : DataBoundControl
{
    public delegate void DataRowColBoundHandler(DataRow rowsrc, string colsrc, HtmlTableCell cell, HtmlTableRow row);
    public delegate void RowColBoundHandler(DataRow rowsrc, int column, HtmlTableCell cell, HtmlTableRow row);
    public delegate void DataBoundHandler();

    public DataRowColBoundHandler DataRowColBound;
    public RowColBoundHandler RowColBound;
    public DataBoundHandler BeforeDataBound;
    public DataBoundHandler AfterDataBound;

    private string cssclass;

    public string CssClass { get { return cssclass; } set { cssclass = value; } }

	public CheckBoxListEx()
	{
	}

    protected override void OnInit(EventArgs e)
    {
        base.OnInit(e);
    }

    protected override void OnLoad(EventArgs e)
    {
        this.Page.RegisterClientScriptBlock("CheckBoxListExScripts", "<script>function ShowOrHideCheckBoxListEx(targetId,dependentId){var cbx=document.getElementById(targetId); var dependent=document.getElementById(dependentId); if(cbx.checked) dependent.style.display = ''; else dependent.style.display = 'none';  }</script>");
        base.OnLoad(e);
    }

    private object datasource;
    public override object DataSource { get { return datasource; } set { datasource = value; } }

    private object datasourceex;
    public object DataSourceEx { get { return datasourceex; } set { datasourceex = value; } }

    private string textfield, valuefield;
    private string matchfield, columns;

    public string DataTextField { get { return textfield; } set { textfield = value; } }
    public string DataValueField { get { return valuefield; } set { valuefield = value; } }
    public string DataMatchField { get { return matchfield; } set { matchfield = value; } }
    public string Columns { get { return columns; } set { columns = value; } }

    protected override void CreateChildControls()
    {
        Controls.Clear();

        if(ViewState["CheckBoxListData"] != null)
            CreateControlHierarchy(false);

        //base.CreateChildControls();
    }

    public override void DataBind()
    {
        base.OnDataBinding(EventArgs.Empty);

        // Create the control hierarchy.  First, clear out the child controls
        Controls.Clear();
        ClearChildViewState();
        TrackViewState();

        // Create the control hierarchy
        CreateControlHierarchy(true);

        // Mark the hierarchy as having been created
        ChildControlsCreated = true;
    }

    HtmlTable mainTable;
    
    protected virtual void CreateControlHierarchy(bool useDataSource)
    {
        mainTable = new HtmlTable();
        Controls.Add(mainTable);

        if (BeforeDataBound != null)
            BeforeDataBound();

        DataTable dt, dtx;
        if (useDataSource)
        {
            dt = (DataTable)datasource;
            //dtx = (DataTable)datasourceex;
        }
        else
        {
            dt = (DataTable)ViewState["CheckBoxListData"];
            //dtx = (DataTable)ViewState["CheckBoxListDataEx"];
        }

        foreach(DataRow dr in dt.Rows)
        {
            HtmlTableRow row = new HtmlTableRow();

            HtmlTableCell checkBoxCell = new HtmlTableCell();
            CheckBox checkBox = new CheckBox();

            if (!string.IsNullOrEmpty(this.DataTextField))
            {
                checkBox.Text = dr[this.DataTextField].ToString();
            }
            else
            {
                checkBox.Text = dr[0].ToString();
            }

            checkBox.ID = this.UniqueID + "_chk" + dr[this.DataValueField].ToString();

            checkBox.CssClass = cssclass;
            checkBoxCell.Controls.Add(checkBox);
            row.Controls.Add(checkBoxCell);



            string[] acolumns = columns.Split(new char[] { ','});

            foreach (string col in acolumns)
            {

                HtmlTableCell dependentCell = new HtmlTableCell();

                //dependentCell.ID = this.ID + "_chk" + dr[this.DataValueField].ToString();

                DataRow rowmatch = null;

                //if (match.Length > 0) rowmatch = match[0];

                if (DataRowColBound != null)
                    DataRowColBound(dr, col, dependentCell, row);

                this.Load += delegate(object sender, EventArgs e)
                {
                    checkBox.Attributes["onclick"] = string.Format("ShowOrHideCheckBoxListEx('{0}','{1}');", checkBox.ClientID, dependentCell.ClientID);
                };

                //if (match.Length > 0)
                //{
                //    checkBox.Checked = true;
                //}
                //else
                //{
                //    dependentCell.Style.Add("display", "none");
                //}

                row.Controls.Add(dependentCell);

            }

            mainTable.Rows.Add(row);
        }

        ViewState["CheckBoxListData"] = dt;
        //ViewState["CheckBoxListDataEx"] = dtx;

        if (AfterDataBound != null)
            AfterDataBound();
   }

    public void SetData(DataTable source)
    {
        DataRow[] match = null;
        string chkPrefix = this.UniqueID + "_chk";
        foreach (HtmlTableRow row in mainTable.Rows)
        {
            int i = 0;
            CheckBox cbx = null;
            foreach (HtmlTableCell cell in row.Cells)
            {
                if (i == 0)
                {
                    cbx = (CheckBox)cell.Controls[0];
                    string lookupvalue = cbx.ID.Substring(chkPrefix.Length);
                    match = source.Select(string.Format("{0}='{1}'", matchfield, lookupvalue));
                }
                else
                {
                    if (match.Length > 1)
                    {
                        cbx.Checked = true;

                        if (RowColBound != null)
                            RowColBound(match[0], i, cell, row);
                    }
                    else
                    {
                        cell.Style.Add("display", "none");
                    }
                }
                i++;
            }
        }
    }

    public DataTable GetData()
    {
        DataTable dt = new DataTable();

        foreach (HtmlTableRow row in mainTable.Rows)
        {
            int i = 0;
            foreach (HtmlTableCell cell in row.Cells)
            {
                if (i == 0)
                {

                }
                else
                {

                }
                i++;
            }
        }

        return dt;
    }

    //public void PopulateControls(DataTable source)
    //{
    //    DataTable dt = (DataTable)datasource;
    //    foreach (DataRow dr in source.Rows)
    //    {
    //       DataRow [] results = dt.Select(string.Format("{0}='{1}'", this.DataTextField, dr[0]));
    //       if (results.Length > 0)
    //       {
    //           results[0]
    //       }
    //    }
    //}

    protected override void Render(HtmlTextWriter writer)
    {
        // Parepare the control hiearchy for rendering
        // PrepareControlHierarchyForRendering();

        // We call RenderContents instead of Render() 
        // so that the encasing tag (<span>)
        // is not included; rather, just a <table> is emitted...
        // RenderContents(writer);
        Controls[0].RenderControl(writer);
    }

}
